package com.hnit.care.controller;

import com.hnit.care.netty.NettyServerHandler;
import io.netty.util.CharsetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Random;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liang
 * @since 2023-07-24
 */
@Controller
@CrossOrigin
public class SendController {

    @Autowired
    NettyServerHandler nettyServerHander;

    // 向服务器发送消息
    @RequestMapping("/sendMessageToServer") //请求路径
    public void sendMessageToMyself(@RequestBody String msg) throws IOException {
        Socket socket = new Socket("localhost",5678); // 创建Socket对象并连接到本地的服务器端口
        OutputStream outputStream = socket.getOutputStream(); //获取连接的输出流
        outputStream.write(msg.getBytes(CharsetUtil.UTF_8)); //转换为字节数组
        outputStream.flush(); //刷新输出流的缓冲区
        socket.shutdownOutput(); //关闭输出流
    }
    /**
     * @param message 向服务器发送的信息
     */
    @RequestMapping("/sendMessageTo")
    public void sendMessageTo(@RequestBody String message) throws InterruptedException {
        message = message.substring(0,message.length()-1);
        System.out.println("主动发消息"+ message);
        Thread.sleep(100+new Random().nextInt(1000)); //停顿一段随机时间(模拟处理耗时)
        nettyServerHander.doAllReplay(message);
    }
}
